<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth;
use app\common\model\Config;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
	    
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('group')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }
	
	function bonus()
	{
		if (false === $this->request->isPost()) {
			return $this->view->fetch();
		}
		$params = $this->request->post('row/a');
		if (empty($params)) {
			$this->error(__('Parameter %s can not be empty', ''));
		}
		$params = $this->preExcludeFields($params);
		
		if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
			$params[$this->dataLimitField] = $this->auth->id;
		}
		$result = false;
		Db::startTrans();
		try {
			//是否采用模型验证
			if ($this->modelValidate) {
				$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
				$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
				$this->model->validateFailException()->validate($validate);
			}
			if ($params['money']<=0){
				throw new Exception('金额不正确');
			}
			$result = $this->vipBonus($params['money']);
			Db::commit();
		} catch (ValidateException|PDOException|Exception|\Throwable $e) {
			Db::rollback();
			$this->error($e->getMessage().$e->getLine());
		}
		if ($result === false) {
			$this->error(__('No rows were inserted'));
		}
		$this->success();
	}
	
	
	#开通会员  所有会籍人员分红
	protected function vipBonus($pay_amount)
	{
		#############START 会籍分红 START####################
		$hehuo_users = \app\admin\model\User::where(['level'=>3])->select();
		$gaoji_users = \app\admin\model\User::where(['level'=>4])->select();
		$zhanlue_users = \app\admin\model\User::where(['level'=>5])->select();

		$hehuo_amount = @($pay_amount * config('site.hehuo_fenhong_ying') /100 / count($hehuo_users));
		$gaoji_amount = @($pay_amount * config('site.gaoji_fenhong_ying')/100 / count($gaoji_users));
		$zhanlue_amount = @($pay_amount * config('site.zhanlue_fenhong_ying')/100 / count($zhanlue_users));
		foreach ($hehuo_users as $hehuo_user){
			\app\common\model\User::money($hehuo_amount, $hehuo_user->id, '分红');
			if ($hehuo_user->parent&&$hehuo_user->parent->level >= $hehuo_user->level){
				//合伙平行
				$hehuo_pingxing_amount = $hehuo_amount * config('site.hehuo_pingxing_fenhong_ying')/100;
				\app\common\model\User::money($hehuo_pingxing_amount, $hehuo_user->parent->id, '分红');
			}
			
			if ($hehuo_user->parent&&in_array($hehuo_user->parent->level,[3,4,5])&&$hehuo_user->parent->level < $hehuo_user->level){
				//越级
				$surpass = $hehuo_user->level - $hehuo_user->parent->level;
				if ($surpass == 1){
					//越1级
					$hehuo_yue1_amount = $hehuo_amount * config('site.hehuo_yue1_fenhong_ying')/100;
					\app\common\model\User::money($hehuo_yue1_amount, $hehuo_user->parent->id, '分红');
				}
				if ($surpass == 2){
					//越2级
					$hehuo_yue2_amount = $hehuo_amount * config('site.hehuo_yue2_fenhong_ying')/100;
					\app\common\model\User::money($hehuo_yue2_amount, $hehuo_user->parent->id, '分红');
				}
			}
		}
		foreach ($gaoji_users as $gaoji_user){
			\app\common\model\User::money($gaoji_amount, $gaoji_user->id, '分红');
			
			if ($gaoji_user->parent&&$gaoji_user->parent->level >= $gaoji_user->level){
				//高级平行
				$gaoji_pingxing_amount = $gaoji_amount * config('site.gaoji_pingxing_fenhong_ying')/100;
				\app\common\model\User::money($gaoji_pingxing_amount, $gaoji_user->parent->id, '分红');
			}
			
			if ($gaoji_user->parent&&in_array($gaoji_user->parent->level,[3,4,5])&&$gaoji_user->parent->level < $gaoji_user->level){
				//越级
				$surpass = $gaoji_user->level - $gaoji_user->parent->level;
				if ($surpass == 1){
					//越1级
					$gaoji_yue1_amount = $gaoji_amount * config('site.gaoji_yue1_fenhong_ying')/100;
					\app\common\model\User::money($gaoji_yue1_amount, $gaoji_user->parent->id, '分红');
				}
				if ($surpass == 2){
					//越2级
					$gaoji_yue2_amount = $gaoji_amount * config('site.gaoji_yue2_fenhong_ying')/100;
					\app\common\model\User::money($gaoji_yue2_amount, $gaoji_user->parent->id, '分红');
				}
			}
		}
		foreach ($zhanlue_users as $zhanlue_user){
			\app\common\model\User::money($zhanlue_amount, $zhanlue_user->id, '分红');
			
			if ($zhanlue_user->parent&&$zhanlue_user->parent->level >= $zhanlue_user->level){
				//战略平行
				$zhanlue_pingxing_amount = $zhanlue_amount * config('site.zhanlue_pingxing_fenhong_ying')/100;
				\app\common\model\User::money($zhanlue_pingxing_amount, $zhanlue_user->parent->id, '分红');
			}
			
			if ($zhanlue_user->parent&&in_array($zhanlue_user->parent->level,[3,4,5])&&$zhanlue_user->parent->level < $zhanlue_user->level){
				//越级
				$surpass = $zhanlue_user->level - $zhanlue_user->parent->level;
				if ($surpass == 1){
					//越1级
					$zhanlue_yue1_amount = $zhanlue_amount * config('site.zhanlue_yue1_fenhong_ying')/100;
					\app\common\model\User::money($zhanlue_yue1_amount, $zhanlue_user->parent->id, '分红');
				}
				if ($surpass == 2){
					//越2级
					$zhanlue_yue2_amount = $zhanlue_amount * config('site.zhanlue_yue2_fenhong_ying')/100;
					\app\common\model\User::money($zhanlue_yue2_amount, $zhanlue_user->parent->id, '分红');
				}
			}
		}
		#############END 会籍分红 END####################
		return true;
	}

}
